﻿using System.Collections;
using System.Configuration;
using System.Web.Routing;
using Common.BaseLibrary;
using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.IoC;
using Common.BaseLibrary.Repositories;
using Common.BaseLibrary.Utils;
using Common.BaseLibrary.Utils.Encryptor;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Commons;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace DepartmentWork.Platform.Controllers
{
    public class HomeController : BaseController
    {
        public List<MenuViewModel> menuModel = null;
        //private IEnumerable<TEAMSPACE> teamspaces;
        //private IEnumerable<USER_INFO> userInfos;
        //private IEnumerable<USER_TEAMSAPCE> userTeamsapces; 

        public HomeController()
        {
            //teamspaces = teamspaceRepository.GetModel().ToList();
            //userInfos = userRepository.GetModel().ToList();
            //userTeamsapces = userTeamsapceRepository.GetModel().ToList();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Login(string flag = "", string returnUrl = "")
        {
            //ViewBag.UserName = ComputerInfoHelper.Instance.GetUserName();
            ViewBag.ReuturnUrl = returnUrl;
            //ViewBag.DomainName = ComputerInfoHelper.Instance.GetConnectionDomainName("127.0.0.1", "0118910", "Bjhg8888");
            IPHostEntry myEntry = new IPHostEntry();
            myEntry = Dns.GetHostByName(Dns.GetHostName());
            ViewBag.DomainName = myEntry.HostName;
            //给界面提示赋值
            if (flag.Trim() != "")
            {
                ViewBag.Flag = flag;
            }

            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(FormCollection collection)
        {
            string userName = collection["tb_UserName"];
            //string domainName = "bj";
            string domainName = "";
            string userPassword = collection["tb_UserPassword"];
            string url = collection["hid_ReuturnUrl"];

            string loginType = collection["select_LoginType"];

            USER_INFO user = new USER_INFO();



            if (loginType == "0")
            {
                #region 用户域登录

                bool result = ComputerInfoHelper.Instance.ImpersonateValidUser
                    (userName, domainName, userPassword);

                //登陆成功获取用户权限
                if (result)
                {

                    user = userRepository.GetModel(r => r.LOGIN_NAME.Contains(userName) && r.ENABLE == "1").FirstOrDefault();

                    if (user == null)
                    {
                        return RedirectToAction("Login", new { flag = "LoginOff" });
                    }
                }
                else
                {
                    return RedirectToAction("Login", new { flag = "LoginOff" });
                }

                #endregion
            }
            else
            {
                #region 表单登录

                string userpwd = Utility.EncryptString(userPassword, Utility.EncryptorType.SHA256);
                user = userRepository.GetModel(r => r.LOGIN_NAME.Contains(userName) && r.PASSWD == userpwd && r.ENABLE == "1").FirstOrDefault();

                #endregion

                if (user == null)
                {
                    return RedirectToAction("Login", new { flag = "LoginOff" });
                }
            }


            #region 获取用户在该团队空间下的所有身份

            List<USER_TEAMSAPCE> userTeamList =
                userTeamsapceRepository.GetModel(u => u.USER_ID == user.USER_ID).ToList();

            Guid teamId = userTeamList[0].TEAMSPACE_ID;

            TEAMSPACE teamspace =
                teamspaceRepository.Find(r => r.TEAMSPACE_ID == teamId);

            string role = "";

            for (int i = 0; i < userTeamList.Count(); i++)
            {
                var item = userTeamList[i];
                role += roleRepository.GetModel(r => r.ROLE_ID == item.ROLE_ID).FirstOrDefault().ROLE_NAME;
            }

            #endregion

            if (!string.IsNullOrEmpty(CurrentUser.UserID))
            {
                CurrentUser.Serialize("", "", "", "", "", 0);
            }

            CurrentUser.Serialize
                (user.USER_ID.ToString(), user.DISPLAY_NAME, "", role, teamspace.TEAMSPACE_NAME);

            if (url!=null&url != "")
            {
                return this.Redirect(url);
            }
            else
            {
                return this.RedirectToAction("Index");
            }



        }

        /// <summary>
        /// 激活用户
        /// </summary>
        /// <returns></returns>
        public ActionResult ActiveUser(Guid teamspaceId, string userId)
        {
            Guid userGuid = Guid.NewGuid();

            #region 判断当前用户是否已经激活

            USER_INFO userCheck = userRepository.GetModel
                (r => r.DISPLAY_NAME.Contains(userId)).FirstOrDefault();

            //if (userCheck.Count() != 0)
            //{
            //    return RedirectToAction("Login", new { flag = "False" });
            //}

            #endregion

            if (userCheck == null || userCheck.LOGIN_NAME.Trim() == "")
            {
                #region 激活当前用户

                //在用户表中添加该用户
                USER_INFO user = new USER_INFO()
                {
                    DISPLAY_NAME = userId,
                    ENABLE = "1",
                    LOGIN_NAME = System.Environment.UserDomainName + @"\" + userId,
                    USER_ID = userGuid
                };

                int roleId = roleRepository.GetModel(r => r.TEAMSPACE_ID == teamspaceId && r.ROLE_NAME == "普通用户")
                    .FirstOrDefault()
                    .ROLE_ID;

                //在用户-团队空间关系表中 添加记录
                USER_TEAMSAPCE userTeam = new USER_TEAMSAPCE()
                {
                    USER_TEAMSAPCE_ID = Guid.NewGuid(),
                    ROLE_ID = roleId,
                    TEAMSPACE_ID = teamspaceId,
                    USER_ID = userGuid
                };

                userRepository.Insert(user);
                userTeamsapceRepository.Insert(userTeam);

                #endregion
            }
            else if (userCheck.ENABLE == "2")
            {
                userCheck.ENABLE = "1";
                userRepository.Update(userCheck);
            }
            else
            {
                return RedirectToAction("Login", new { flag = "False" });
            }

            return RedirectToAction("Login", new { flag = "Active" });
        }


        [HttpGet]
        public ActionResult Index(string info = "", string type = "")
        {
            List<UserTaskViewModel> taskList = new List<UserTaskViewModel>();
            ViewBag.Info = info;
            USER_INFO user = new USER_INFO();
            string userName = "";
            try
            {
                userName = ComputerInfoHelper.Instance.GetUserName().Split('\\')[1];
            }
            catch (Exception)
            {
                //userName = ComputerInfoHelper.Instance.GetUserName();
                userName = HttpContext.User.Identity.Name.Split('\\')[1];
            }

            if (string.IsNullOrEmpty(CurrentUser.UserID) && type != "anonymity")
            {
                user = userRepository.GetModel(r => r.DOMAIN_NAME.Contains(userName)&& r.ENABLE=="1" ).FirstOrDefault();

                //if (user.LOGIN_NAME != null && user.LOGIN_NAME != "" )
                if (user != null)
                {
                    #region 获取用户在该团队空间下的所有身份

                    List<USER_TEAMSAPCE> userTeamList =
                        userTeamsapceRepository.GetModel(u => u.USER_ID == user.USER_ID).ToList();

                    Guid teamId = userTeamList[0].TEAMSPACE_ID;

                    TEAMSPACE teamspace =
                        teamspaceRepository.Find(r => r.TEAMSPACE_ID == teamId);

                    string role = "";

                    for (int i = 0; i < userTeamList.Count(); i++)
                    {
                        var item = userTeamList[i];
                        role += roleRepository.GetModel(r => r.ROLE_ID == item.ROLE_ID).FirstOrDefault().ROLE_NAME;
                    }

                    #endregion



                    CurrentUser.Serialize
                        (user.USER_ID.ToString(), user.DISPLAY_NAME, "", role, teamspace.TEAMSPACE_NAME);
                }
            }

            List<NewInfoModel> listOfProjectManageInfo = new List<NewInfoModel>();
            List<NewInfoModel> listOfMaintenanceInfo = new List<NewInfoModel>();
            List<NewInfoModel> listOfDeskWorksInfo = new List<NewInfoModel>();

            List<PROJECT_WORKRECORD> listRecord = projectWorkReocredRepository.GetModel().OrderByDescending(r => r.PROJECT_WORKRECORD_CREATETIME).Take(5).ToList();

            for (int i = 0; i < listRecord.Count; i++)
            {
                NewInfoModel item = new NewInfoModel();
                item.Info_Id = listRecord[i].PROJECT_WORKRECORD_ID;
                item.CreateTime = listRecord[i].PROJECT_WORKRECORD_CREATETIME;
                item.Content = listRecord[i].PROJECT_WORKRECORD_TITLE;
                item.TypeName = "项目管理工作进展";
                Guid? id = listRecord[i].PROJECT_MANAGEMENT_ID;
                if (id!=null)
                {
                    item.ProjectName = projectManagementRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == id).FirstOrDefault().PROJECT_MANAGEMENT_TITLE;
                }
                else
                {
                    item.ProjectName = "其他项目工作";
                }
                   
                listOfProjectManageInfo.Add(item);
            }

            List<PROJECT_MAINTENANCE_RECORD> listMaintenceRecord = projectMaintenanceRecordRepository.GetModel().OrderByDescending(r => r.RECORD_TIME).Take(5).ToList();

            for (int i = 0; i < listMaintenceRecord.Count; i++)
            {
                NewInfoModel item=new NewInfoModel();
                item.Info_Id = listMaintenceRecord[i].RECORD_ID;
                item.CreateTime = listMaintenceRecord[i].RECORD_TIME;
                item.TypeName = "运维工作进展";
                item.Content = listMaintenceRecord[i].RECORD_NAME;
                Guid id = listMaintenceRecord[i].RECORD_OPERATION_ID;
                item.ProjectName = projectMaintenanceAppopsRepository.GetModel(r => r.APPOPS_ID == id).FirstOrDefault().APPOPS_NAME;
                listOfMaintenanceInfo.Add(item);
            }

            List<PROJECT_DESK_WORK> listDeskWorks= projectdeskworkRepository.GetModel().OrderByDescending(r => r.DESKWORK_CREATETIME).Take(5).ToList();

            for (int i = 0; i < listDeskWorks.Count; i++)
            {
                NewInfoModel item = new NewInfoModel();
                item.TypeName = "科室工作进展";
                item.Info_Id = listDeskWorks[i].DESKWORK_ID;
                item.Content = listDeskWorks[i].DESKWORK_NAME;
                item.CreateTime = listDeskWorks[i].DESKWORK_CREATETIME;
                item.ProjectName = listDeskWorks[i].DESKWORK_NAME;
                listOfDeskWorksInfo.Add(item);
            }

            ViewBag.ListOfProjectManageInfo = listOfProjectManageInfo;
            ViewBag.ListOfMaintenanceInfo = listOfMaintenanceInfo;
            ViewBag.ListDeskWorks = listOfDeskWorksInfo;

            if (!string.IsNullOrEmpty(CurrentUser.UserID))
            {
                Guid userId = new Guid(CurrentUser.UserID);

                #region 获取用户代办


                #region 获取用户BUG的代办

                List<PROJECT_DEVELOP_BUG> bugTaskList = projectDevelopBugRepository.GetModel(b => b.HANDTO_USER == userId && b.CHECK_FLAG == 0).ToList();

                #endregion

                #region 获取用户任务的代办

                List<PROJECT_DEVELOP_TASK> devTaskList =
                    projectDevelopTaskRepository.GetModel
                    (b => b.HANDTO_USER == userId && b.CHECK_FLAG == 0).ToList();

                #endregion

                #region 获取用户科室工作的代办

                List<PROJECT_DESK_WORK> DeskWorkList = projectdeskworkRepository.GetModel(r => r.DESKWORK_PRINCIPAL_ID == userId && r.DESKWORK_STATUS == "0").ToList();

                #endregion

                #region 获取用户运维工作的代办


                List<PROJECT_MAINTENANCE_APPOPS_USER> appopsUser = projectMaintenanceAppopsUserRepository.GetModel(r => r.APPOPS_PRINCIPAL_USER_ID == userId).ToList();
                List<PROJECT_MAINTENANCE_APPOPS> appopsList = new List<PROJECT_MAINTENANCE_APPOPS>();

                if (appopsUser.Count > 0)
                {
                    foreach (PROJECT_MAINTENANCE_APPOPS_USER xx in appopsUser)
                    {
                        appopsList.AddRange(projectMaintenanceAppopsRepository.GetModel(r => r.APPOPS_ID == xx.APPOPS_APPOPS_ID && r.APPOPS_STATE == "0").ToList());
                    }
                }
                #endregion

                #region 获取用户审批请假的代办

                List<PROJECT_DESK_WORKTIME> worktimeList = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_OVERNAME == userId && r.WORKTIME_STATUS == 0).ToList();

                #endregion

                #region 获取用户审批请假的代办

                List<PROJECT_DESK_LEAVE> leaveList = projectdeskleaveRepository.GetModel(r => r.LEAVE_OVERNAME == userId && r.LEAVE_APPROVERRESULT == "0").ToList();

                #endregion




                if (bugTaskList.Count() != 0)
                {
                    taskList.AddRange((from item in bugTaskList
                                       select new UserTaskViewModel()
                                       {
                                           CreateTime = item.CREATETIME,
                                           TaskId = item.BUG_ID,
                                           Title = item.BUG_NAME,
                                           Type = "BUG"
                                       }).ToList());
                }

                if (devTaskList.Count() != 0)
                {
                    taskList.AddRange((from item in devTaskList
                                       select new UserTaskViewModel()
                                       {
                                           CreateTime = item.CREATE_TIME,
                                           TaskId = item.TASK_ID,
                                           Title = item.TASK_NAME,
                                           Type = "任务"
                                       }).ToList());
                }


                if (DeskWorkList.Count() != 0)
                {
                    taskList.AddRange((from item in DeskWorkList
                                       select new UserTaskViewModel()
                                       {
                                           CreateTime = item.DESKWORK_CREATETIME,
                                           TaskId = item.DESKWORK_ID,
                                           Title = item.DESKWORK_NAME,
                                           Type = "科室工作"
                                       }).ToList());
                }

                if (appopsList.Count() != 0)
                {
                    taskList.AddRange((from item in appopsList
                                       select new UserTaskViewModel()
                                       {
                                           CreateTime = item.APPOPS_TIME,
                                           TaskId = item.APPOPS_ID,
                                           Title = item.APPOPS_NAME,
                                           Type = "运维工作"
                                       }).ToList());
                }

                if (worktimeList.Count() != 0)
                {
                    taskList.AddRange((from item in worktimeList
                                       select new UserTaskViewModel()
                                       {
                                           CreateTime = item.WORKTIME_TIME,
                                           TaskId = item.WORKTIME_ID,
                                           Title = userRepository.Find(r => r.USER_ID == item.WORKTIME_NAMEID).DISPLAY_NAME.ToString(),
                                           Type = "加班申请"
                                       }).ToList());
                }

                if (leaveList.Count() != 0)
                {
                    taskList.AddRange((from item in leaveList
                                       select new UserTaskViewModel()
                                       {
                                           CreateTime = item.LEAVE_TIME,
                                           TaskId = item.LEAVE_ID,
                                           Title = userRepository.Find(r => r.USER_ID == item.Leave_NAMEID).DISPLAY_NAME.ToString(),
                                           Type = "请假申请"
                                       }).ToList());
                }
                #endregion
            }
            else
            {
                //匿名用户
                CurrentUser.Serialize
                    ("", "匿名用户", "", "", "匿名空间");
            }


            return this.View(taskList);
        }


        public ViewResult MenuPage()
        {
            if (menuModel == null)
            {
                menuModel = new List<MenuViewModel>();
                List<MENU> menuList = menuRepository.GetModel(r=>r.MENU_STATUS==0).ToList();
                menuModel.AddRange((from item in menuList
                                    select new MenuViewModel()
                                    {
                                        ACTION_NAME = item.ACTION_NAME,
                                        AREA_NAME = item.AREA_NAME,
                                        BOOT_MENU_ID = item.BOOT_MENU_ID,
                                        CONTROLLER_NAME = item.CONTROLLER_NAME,
                                        MENU_CONTEXT = item.MENU_CONTEXT,
                                        MENU_ID = item.MENU_ID,
                                        MENU_NAME = item.MENU_NAME,
                                        MENU_STATUS = item.MENU_STATUS,
                                        MENU_CLASS = item.MENU_CLASS
                                    }).ToList());

                for (int i = 0; i < menuModel.Count(); i++)
                {
                    int id = menuModel[i].MENU_ID;
                    menuModel[i].CHILDEN_COUNT = menuModel.FindAll(r => r.BOOT_MENU_ID == id).Count();
                }
            }


            return this.View(menuModel.OrderBy(r => r.MENU_ID).ToList());
        }

        [HttpGet()]
        public ActionResult DownLoadFile(string filePath, string type, string fileName)
        {

            string fileFullPath = Path.Combine(ConfigurationManager.AppSettings["UpLoadPath"], type, fileName);

            //filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);
            FileStream fs = new FileStream(fileFullPath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.Charset = "UTF-8";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Response.ContentType = "application/octet-stream";

            Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(filePath));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            return this.Content("<script>alert('文件下载成功');</script>");

        }


        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public ActionResult LogOut()
        {
            CurrentUser.Exit();
            return RedirectToAction("login", "Home", new { area = "" });
        }

    }
}